// pages/address/address.js

const app = getApp();
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    openId: app.globalData.openId,
    addressList: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    if (app.globalData.userInfo) {
      wx.request({
        url: app.globalData.apiDomain + '/api/address/find',
        method: "POST",
        data: {
          openId: app.globalData.openId
        },
        success: function(res) {
          that.setData({
            addressList: res.data.data
          });
        }
      })
    } else {
      wx.switchTab({
        url: '../userCenter/userCenter',
        complete: function() {
          wx.showToast({
            title: '请先登录',
            image: '../../images/failure_toast.png',
            duration: 2000,
          });
        }
      })
    }


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  navigatorToEdit: util.throttle(function(e) {
    wx.redirectTo({
      url: '../address-edit/address-edit?resource=1',
    })
  }),
  goEdit: util.throttle(function(e) {
    wx.redirectTo({
      url: '../address-edit/address-edit?resource=1&id=' + e.currentTarget.dataset.addressId,
    })
  }),
  delete: util.throttle(function(e) {
    wx.showModal({
      title: '温馨提示',
      content: '确定要删除该条地址吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: function(res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.apiDomain + '/api/address/delete',
            method: "POST",
            data: {
              id: e.currentTarget.dataset.addressId
            },
            success: function(res) {
              wx.redirectTo({
                url: '../address/address',
              })
            }
          })
        } else if (res.cancel) {}
      },
    })
  })

})